import { ElMessageBoxOptions, Message } from "element-plus";
import { ApiException, HttpValidationProblemDetails } from "./client";
import { h } from "vue";

class HttpValidationProblemDetailsHelper {
  constructor() {}

  static isHttpValidationProblem(
    obj: any
  ): obj is HttpValidationProblemDetails {
    return obj.status && typeof obj.status === "number";
  }
}

const useRequestExceptionHandler = (
  msg: Message,
  msgBox: (msgBoxOptions: ElMessageBoxOptions) => void
) => {
  return (err: Error | ApiException | HttpValidationProblemDetails) => {
    console.log(`接口请求失败:`, { ...err });

    if (ApiException.isApiException(err)) {
      msg.error(`${err.message} (${err.status})`);
    } else if (
      HttpValidationProblemDetailsHelper.isHttpValidationProblem(err)
    ) {
      if (err.errors) {
        const fields = Object.keys(err.errors);
        msgBox({
          title: err.title,
          message: h(
            "ElRow",
            fields.map((field) => {
              return [
                h("ElCol", [h("strong", field)]),
                h("ElCol", [
                  h(
                    "ul",
                    err.errors?.[field].map((errorItem) => {
                      return h("li", errorItem);
                    })
                  ),
                ]),
              ];
            })
          ),
        });
      } else {
        msgBox({
          title: err.title,
          message: err.detail,
        });
      }
    } else {
      msg.error(`未处理的异常: ${err.message}`);
    }
  };
};

const clientHelper = {
  useRequestExceptionHandler,
  HttpValidationProblemDetailsHelper,
};

export default clientHelper;
